package com.qd.panda.service.space;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.DateUtil;
import com.cdqidi.util.RedisTemplateUtil;
import com.cdqidi.util.SpringContextHolder;
import com.qd.common.panda.domain.entity.space.OwnParkSpaceTenantDTO;
import com.qd.common.panda.domain.entity.space.ParkSpaceTenantDTO;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.panda.mapper.space.ParkSpaceTenantMapper;
import com.qd.panda.model.ParkSpaceTenant;
import com.qd.panda.service.stroke.DisplayUtil;
import com.qd.system.service.login.LoginUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;

/**
 * 承租信息
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ParkSpaceTenantService extends BaseService<ParkSpaceTenantMapper, ParkSpaceTenant> {

    private static final String PREFIX_ID = "panda_park_space_tenant_id_{0}";
    private static final String PREFIX_LIST = "panda_park_space_tenant_sid_{0}";

    private final RedisTemplateUtil<ParkSpaceTenant> redisTemplateUtil;
    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public ParkSpaceTenantDTO save(ParkSpaceTenantDTO dto) {
        final ParkSpaceTenant model = dtoToModel(dto);
        if (null != getUniqueByStartDateAndEndDateAndSid(model.getStartDate(), model.getEndDate(), model.getStartHour(), model.getEndHour(), dto.getSid())) {
            throw new ApiException("数据已存在，请勿重复操作");
        }
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public ParkSpaceTenantDTO update(ParkSpaceTenantDTO dto) {
        final ParkSpaceTenant historyModel = Optional.ofNullable(getById(dto.getId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final ParkSpaceTenant model = dtoToModel(dto);
        try{
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        }finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<ParkSpaceTenant> mList) {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<ParkSpaceTenant> mList) {
        final List<String> ids = mList.stream().map(ParkSpaceTenant::getId).collect(toList());
        final List<ParkSpaceTenant> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param id 主键 
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String id) {
        final ParkSpaceTenant historyModel = Optional.ofNullable(getById(id)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(id)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        final List<ParkSpaceTenant> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(ParkSpaceTenantDTO dto) {
        final QueryWrapper<ParkSpaceTenant> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param id 主键 
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String id) {
        boolean exists = false;
        if (StringUtils.hasLength(id)) {
            final ParkSpaceTenant model = getById(id);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param id 主键 
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public ParkSpaceTenant getById(String id) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, id);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(id), ParkSpaceTenant.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param id 主键 
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public ParkSpaceTenantDTO getByIdDto(String id) {
        return Optional.ofNullable(getById(id)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public ParkSpaceTenant getOne(ParkSpaceTenantDTO dto) {
        final QueryWrapper<ParkSpaceTenant> queryWrapper = createQueryWrapper(dto);
        ParkSpaceTenant model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public ParkSpaceTenantDTO getOneDto(ParkSpaceTenantDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<ParkSpaceTenant> getList(ParkSpaceTenantDTO dto) {
        final QueryWrapper<ParkSpaceTenant> queryWrapper = createQueryWrapper(dto);
        final List<ParkSpaceTenant> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<ParkSpaceTenantDTO> getListDto(ParkSpaceTenantDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<ParkSpaceTenantDTO> page(Page<ParkSpaceTenant> page, ParkSpaceTenantDTO dto) {
        final QueryWrapper<ParkSpaceTenant> queryWrapper = createQueryWrapper(dto, "t1.");
        final IPage<ParkSpaceTenantDTO> iPage = baseMapper.page(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(l-> l.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 车主端，我的订单
     *
     * @param page 分页对象
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<OwnParkSpaceTenantDTO> carOwnOrderPage(IPage<OwnParkSpaceTenantDTO> page) {
        IPage<OwnParkSpaceTenantDTO> iPage = baseMapper.carOwnOrderPage(page, SecurityUtils.getLoginUser().getUserId());
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        return iPage;
    }

    /**
     * 车主端，我的订单详情
     *
     * @param id 主键
     * @return 数据
     */
    @Transactional(readOnly = true)
    public OwnParkSpaceTenantDTO carOwnOrderById(String id) {
        OwnParkSpaceTenantDTO ownParkSpaceTenantDTO = baseMapper.carOwnOrderById(id);
        Optional.ofNullable(ownParkSpaceTenantDTO).ifPresent(this::buildDisplay);
        return ownParkSpaceTenantDTO;
    }

    private void buildDisplay(OwnParkSpaceTenantDTO ownParkSpaceTenantDTO) {
        //0拍下未付款1付款成功2付款失败7申请退款8退款成功9退款失败
        ownParkSpaceTenantDTO.setTenantOrderStateDisplay(TenantOrderStateUtilService.idToDisplay(ownParkSpaceTenantDTO.getTenantOrderState()));
        ownParkSpaceTenantDTO.setTotalCostDisplay(ownParkSpaceTenantDTO.getTotalCost().stripTrailingZeros().toPlainString());
        ownParkSpaceTenantDTO.setDayPriceDisplay(ownParkSpaceTenantDTO.getDayPrice().stripTrailingZeros().toPlainString());
    }



    /**
     * 根据唯一性索引获得数据
     * param startDate 
     * param endDate 
     * param sid 
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public ParkSpaceTenant getUniqueByStartDateAndEndDateAndSid(LocalDate startDate, LocalDate endDate, LocalTime startHour, LocalTime endHour, String sid) {
        final QueryWrapper<ParkSpaceTenant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("start_date", startDate);
        queryWrapper.eq("end_date", endDate);
        queryWrapper.eq("start_hour", startHour);
        queryWrapper.eq("end_hour", endHour);
        queryWrapper.eq("sid", sid);
        queryWrapper.in("tenant_order_state", TenantOrderStateUtilService.STATE_0, TenantOrderStateUtilService.STATE_1);
        ParkSpaceTenant parkSpaceTenant = super.getOne(queryWrapper, false);
        queryWrapper.clear();
        return parkSpaceTenant;
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(ParkSpaceTenant model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, model.getSid()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<ParkSpaceTenant> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
        Set<String> sidList = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, model.getSid())).collect(toSet());
        if (!sidList.isEmpty()) {
            redisTemplateUtil.deleteByKey(sidList);
            sidList.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public ParkSpaceTenantDTO modelToDto(ParkSpaceTenant model) {
        if (null == model) {
            return null;
        }
        final ParkSpaceTenantDTO dto = new ParkSpaceTenantDTO();
        dto.setId(model.getId());
        dto.setStartDate(DateUtil.localDateToStr(model.getStartDate()));
        dto.setEndDate(DateUtil.localDateToStr(model.getEndDate()));
        Optional.ofNullable(model.getStartHour()).ifPresent(startHour -> dto.setStartHour(DateUtil.localTimeToString(startHour)));
        Optional.ofNullable(model.getEndHour()).ifPresent(endHour -> dto.setEndHour(DateUtil.localTimeToString(endHour)));
        dto.setDays(model.getDays());
        dto.setActualDays(model.getActualDays());
        dto.setDeductionTotalRevenue(model.getDeductionTotalRevenue());
        dto.setDayPrice(model.getDayPrice());
        dto.setTotalCost(model.getTotalCost());
        dto.setRefundAmount(model.getRefundAmount());
        dto.setDeductionAmount(model.getDeductionAmount());
        dto.setRefundTime(model.getRefundTime());
        dto.setRefundReason(model.getRefundReason());
        dto.setRefundNote(model.getRefundNote());
        dto.setTenantOrderState(model.getTenantOrderState());
        dto.setSid(model.getSid());
        dto.setTenant(model.getTenant());
        dto.setOrderTime(model.getOrderTime());
        dto.setTenantNumber(model.getTenantNumber());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public ParkSpaceTenant dtoToModel(ParkSpaceTenantDTO dto) {
        if (null == dto) {
            return null;
        }
        final ParkSpaceTenant model = new ParkSpaceTenant();
        model.setId(dto.getId());
        model.setStartDate(DateUtil.strToLocalDate(dto.getStartDate()));
        model.setEndDate(DateUtil.strToLocalDate(dto.getEndDate()));
        Optional.ofNullable(dto.getStartHour()).ifPresent(startHour -> model.setStartHour(DateUtil.strToLocalTime(startHour)));
        Optional.ofNullable(dto.getEndHour()).ifPresent(endHour -> model.setEndHour(DateUtil.strToLocalTime(endHour)));
        model.setDays(dto.getDays());
        model.setActualDays(dto.getActualDays());
        model.setDeductionTotalRevenue(dto.getDeductionTotalRevenue());
        model.setDayPrice(dto.getDayPrice());
        model.setTotalCost(dto.getTotalCost());
        model.setRefundAmount(dto.getRefundAmount());
        model.setDeductionAmount(dto.getDeductionAmount());
        model.setRefundTime(dto.getRefundTime());
        model.setRefundReason(dto.getRefundReason());
        model.setRefundNote(dto.getRefundNote());
        model.setTenantOrderState(dto.getTenantOrderState());
        model.setSid(dto.getSid());
        model.setTenant(dto.getTenant());
        model.setOrderTime(dto.getOrderTime());
        model.setTenantNumber(dto.getTenantNumber());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(ParkSpaceTenantDTO dto) {
        dto.setTenantDisplay(SpringContextHolder.getBean(LoginUserService.class).idToDisplay(dto.getTenant()));
        dto.setDeductionAmountDisplay(dto.getDeductionAmount().stripTrailingZeros().toPlainString());
        dto.setDeductionTotalRevenueDisplay(dto.getDeductionTotalRevenue().stripTrailingZeros().toPlainString());
        dto.setRefundAmountDisplay(dto.getRefundAmount().stripTrailingZeros().toPlainString());
        dto.setTotalCostDisplay(dto.getTotalCost().stripTrailingZeros().toPlainString());
        Optional.ofNullable(dto.getDayPrice()).ifPresent(price -> dto.setDayPriceDisplay(price.stripTrailingZeros().toPlainString()));
        dto.setTenantOrderStateDisplay(TenantOrderStateUtilService.idToDisplay(dto.getTenantOrderState()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<ParkSpaceTenantDTO> modelToDtoList(List<ParkSpaceTenant> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<ParkSpaceTenant> dtoToModelList(List<ParkSpaceTenantDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<ParkSpaceTenant> createQueryWrapper(ParkSpaceTenantDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<ParkSpaceTenant> createQueryWrapper(ParkSpaceTenantDTO dto, String tableAlias) {
        final QueryWrapper<ParkSpaceTenant> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getRefundReason())) {
                queryWrapper.eq(tableAlias + "refund_reason", dto.getRefundReason());
            }
            if (StringUtils.hasLength(dto.getRefundNote())) {
                queryWrapper.eq(tableAlias + "refund_note", dto.getRefundNote());
            }
            if (StringUtils.hasLength(dto.getSid())) {
                queryWrapper.eq(tableAlias + "sid", dto.getSid());
            }
            if (StringUtils.hasLength(dto.getTenant())) {
                queryWrapper.eq(tableAlias + "tenant", dto.getTenant());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<ParkSpaceTenant> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<ParkSpaceTenant> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(ParkSpaceTenant::getId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    @Transactional(readOnly = true)
    public List<ParkSpaceTenantDTO> getListBySidDto(String sid) {
        return modelToDtoList(getListBySid(sid));
    }

    @Transactional(readOnly = true)
    public List<ParkSpaceTenant> getListBySid(String sid) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, sid);
        return redisTemplateUtil.getList(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> {
            QueryWrapper<ParkSpaceTenant> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sid", sid);
            queryWrapper.orderByAsc("order_time");
            queryWrapper.orderByAsc("tenant_order_state");
            List<ParkSpaceTenant> list = super.list(queryWrapper);
            queryWrapper.clear();
            return list;
        }, ParkSpaceTenant.class);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeBySid(String sid) {
        List<ParkSpaceTenant> list = getListBySid(sid);
        if (!list.isEmpty()) {
            throw new ApiException("已经有人租赁不能删除");
        }
    }

    @Transactional(readOnly = true)
    public List<ParkSpaceTenant> getPaySuccess(String sid) {
        List<ParkSpaceTenant> list = getListBySid(sid);
        if(!list.isEmpty()){
            return list.stream().filter(p -> p.getTenantOrderState() == 1).collect(toList());
        }
        return list;
    }

    @Transactional(readOnly = true)
    public ParkSpaceTenantDTO getLastBySid(String sid, LocalDate localDate, LocalTime localTime) {
        QueryWrapper<ParkSpaceTenant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sid", sid);
        queryWrapper.eq("tenant_order_state", 1);
        if (null != localDate) {
            queryWrapper.ge("end_date", localDate);
        }
        if (null != localTime) {
            queryWrapper.ge("end_hour", localTime);
        }
        queryWrapper.last("limit 1");
        queryWrapper.orderByAsc("abs(DATEDIFF("+localDate+", end_date))");
        if (null != localTime) {
            queryWrapper.orderByAsc("abs(DATEDIFF("+localTime+", end_hour))");
        }
        ParkSpaceTenant parkSpaceTenant = baseMapper.selectOne(queryWrapper, false);
        queryWrapper.clear();
        return modelToDto(parkSpaceTenant);
    }

    @Transactional(readOnly = true)
    public Long getOrderBySid(String sid) {
        QueryWrapper<ParkSpaceTenant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sid", sid);
        queryWrapper.eq("tenant_order_state", 1);
        Long count = baseMapper.selectCount(queryWrapper);
        queryWrapper.clear();
        return null == count ? 0 : count;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateTenantOrderState(String bid, Integer refundStatus) {
        log.info("updateTenantOrderState,bid: {},refundStatus:{}", bid, refundStatus);
        ParkSpaceTenantDTO parkSpaceTenantDTO = Optional.ofNullable(getByIdDto(bid)).orElseThrow(() -> new ApiException("ID值不存在"));
        log.info("updateTenantOrderState,tenantOrderState: {}", parkSpaceTenantDTO.getTenantOrderState());
        if (parkSpaceTenantDTO.getTenantOrderState().equals(DisplayUtil.PAY_STATUS_1) || parkSpaceTenantDTO.getTenantOrderState().equals(DisplayUtil.PAY_STATUS_7)) {
            if (refundStatus.equals(DisplayUtil.REFUND_STATUS_1)) {
                parkSpaceTenantDTO.setTenantOrderState(DisplayUtil.PAY_STATUS_8);
            }
            if (refundStatus.equals(DisplayUtil.REFUND_STATUS_2)) {
                parkSpaceTenantDTO.setTenantOrderState(DisplayUtil.PAY_STATUS_9);
            }
            update(parkSpaceTenantDTO);
            parkSpaceTenantDTO.freeData();
        }
    }
}